//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package com.ruoyi.live.user.service;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.ruoyi.live.app.service.CacheService;
import com.ruoyi.live.configuration.SessionInfo;
import com.ruoyi.live.base.domain.*;
import com.ruoyi.live.base.mapper.*;
import com.ruoyi.live.tool.commons.ICommons;
import com.ruoyi.live.tool.commons.IConvert;
import com.ruoyi.live.tool.commons.IMD5;
import com.ruoyi.live.tool.utils.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.ModelAndView;

import java.util.*;
import java.util.Map.Entry;
import java.util.stream.Collectors;

@Service
public class StudentService {
    @Autowired
    UserMapper userDao;
    @Autowired
    CacheService cacheService;
    @Autowired
    JdbcTemplate jdbcTemplate;
    @Autowired
    TaskCatalogMapper catalogDao;
    @Autowired
    TaskSourceMapper taskSourceDao;
    @Autowired
    TaskUserLearnLogMapper logDao;
    @Autowired
    LiveExamMapper examDao;
    @Autowired
    TaskMapper taskDao;
    @Autowired
    TaskUserLearnLogMapper learnLogDao;

    public StudentService() {
    }

    public Message updatePsdSave(String userpass, String userpassnew) {
        User user = SessionInfo.getUser();
        if (user.getUserPasswordMd5().equals(IMD5.getMD5(userpass))) {
            user.setUserPasswordMd5(IMD5.getMD5(userpassnew));
            this.userDao.updateById(user);
            return new Message(true, "修改成功");
        } else {
            return new Message(false, "登录密码错误");
        }
    }

    public List<TaskCatalog> getTasks() {
        List<TaskCatalog> list = this.cacheService.getTasks();
        List<TaskUserLearnLog> tasks = this.logDao.selectList(new QueryWrapper((new TaskUserLearnLog()).setCreateUser(SessionInfo.getUserId())));
        Map<Long, TaskUserLearnLog> map = (Map)tasks.stream().collect(Collectors.toMap(TaskUserLearnLog::getTaskId, (st) -> {
            return st;
        }));
        Iterator var4 = list.iterator();

        while(var4.hasNext()) {
            TaskCatalog cata = (TaskCatalog)var4.next();
            Iterator var6 = cata.getTasks().iterator();

            while(var6.hasNext()) {
                Task task = (Task)var6.next();
                TaskUserLearnLog mst = (TaskUserLearnLog)map.get(task.getId());
                if (mst != null) {
                    task.setMstId(mst.getId());
                    task.setStudentTaskState(mst.getState());
                } else {
                    task.setStudentTaskState((Integer)null);
                }
            }
        }

        return list;
    }

    public List<TaskCatalog> listTasksByParam(Task param) {
        String sql = "select aaa.* from (select a.*,ifnull(b.state,-1) student_task_state,b.id mst_id from task a left join (select c.state,c.task_id,c.id from task_user c where c.state in (1,2) and c.create_user = ?) b on b.task_id = a.id order by orders) aaa where 1=1 ";
        if (!ICommons.isNullOrEmpty(param.getState())) {
            sql = sql + " and aaa.student_task_state = " + param.getState();
        }

        if (!ICommons.isNullOrEmpty(param.getPlatformId())) {
            sql = sql + " and aaa.catalog_id = " + param.getPlatformId();
        }

        if (!ICommons.isNullOrEmpty(param.getTaskName())) {
            sql = sql + " and aaa.task_name like '%" + param.getTaskName() + "%'";
        }

        List<Task> tasks = this.jdbcTemplate.query(sql, new Object[]{SessionInfo.getUserId()}, new BeanPropertyRowMapper(Task.class));
        List<TaskCatalog> list = this.catalogDao.selectList((Wrapper)(new QueryWrapper(new TaskCatalog())).orderByAsc("orders"));
        Map<Long, TaskCatalog> map = (Map)list.stream().collect(Collectors.toMap(TaskCatalog::getId, (cata) -> {
            return cata;
        }));
        Iterator var6 = tasks.iterator();

        while(var6.hasNext()) {
            Task task = (Task)var6.next();
            TaskCatalog mc = (TaskCatalog)map.get(task.getCatalogId());
            task.setPlatformId(mc.getPlatformId());
            List<Task> ts = mc.getTasks();
            if (ts == null) {
                ts = new ArrayList();
                ts.add(task);
                ((TaskCatalog)map.get(task.getCatalogId())).setTasks(ts);
            } else {
                ts.add(task);
            }
        }

        List<TaskCatalog> res = new ArrayList();
        Iterator var11 = map.entrySet().iterator();

        while(var11.hasNext()) {
            Entry<Long, TaskCatalog> entry = (Entry)var11.next();
            TaskCatalog mt = (TaskCatalog)entry.getValue();
            if (mt.getTasks() != null) {
                mt.setCount(mt.getTasks().size());
                res.add(mt);
            }
        }

        return res;
    }

    public Map<String, Object> getSourceParams(Long id) {
        Map<String, Object> res = new HashMap();
        List<TaskSource> sources = this.taskSourceDao.selectList(new QueryWrapper((new TaskSource()).setType(1).setTaskId(id)));
        if (sources.size() > 0) {
            res.put("al", ((TaskSource)sources.get(0)).getId());
        }

        sources = this.taskSourceDao.selectList(new QueryWrapper((new TaskSource()).setType(3).setTaskId(id)));
        if (sources.size() > 0) {
            res.put("dx", ((TaskSource)sources.get(0)).getId());
        }

        return res;
    }

    public ModelAndView openSource(Long id) {
        TaskSource source = (TaskSource)this.taskSourceDao.selectById(id);
        return (new ModelAndView(this.getSourceJspPath(source))).addObject("obj", source);
    }

    public String getSourceJspPath(TaskSource source) {
        String ext = source.getFileUrl().substring(source.getFileUrl().indexOf(".") + 1);
        String pageName = "/task/preview/preview_pic";
        if ("pdf".contains(ext)) {
            pageName = "/task/preview/preview_pdf";
        } else if ("mp4".equals(ext) || "flv".equals(ext)) {
            pageName = "/task/preview/preview_video";
        }

        return pageName;
    }

    public List<TaskSource> getSourceList(Long id) {
        List<TaskSource> res = this.taskSourceDao.selectList(new QueryWrapper((new TaskSource()).setType(2).setTaskId(id)));
        Iterator var3 = res.iterator();

        while(var3.hasNext()) {
            TaskSource mts = (TaskSource)var3.next();
            String path = this.getSourceJspPath(mts);
            int fileType = 1;
            if (path.contains("pdf")) {
                fileType = 2;
            } else if (path.contains("video")) {
                fileType = 3;
            }

            mts.setIframeUrl(path + "/" + mts.getId());
            mts.setFileType(Integer.valueOf(fileType));
        }

        return res;
    }

    public void insertLog(Long id) {
        Long count = this.logDao.selectCount(new QueryWrapper((new TaskUserLearnLog()).setCreateUser(SessionInfo.getUserId()).setTaskId(id)));
        if (count == 0l) {
            LiveExam exam = (LiveExam)this.examDao.selectOne(new QueryWrapper((new LiveExam()).setExamType(1).setTaskId(id)));
            Task task = (Task)this.taskDao.selectById(id);
            if (exam != null) {
                this.logDao.insert((new TaskUserLearnLog()).setTaskId(id).setClassId(SessionInfo.getClassId()).setCreateTime(System.currentTimeMillis()).setCreateUser(SessionInfo.getUserId()).setExamId(exam.getId()).setState(1).setCatalogId(task.getCatalogId()).setScoreState(1));
            }
        }

    }

    public List<Map<String, Object>> getMaxs() {
        Long classId = SessionInfo.getClassId();
        String sql = "select aaa.*,bbb.user_login_name name from (select aa.*,(@ranknum:=@ranknum+1) as rank from (select round(max(score),2) score,create_user from task_user_learn_log a where a.state = 2 and a.class_id = ?  and a.score_state = 2 group by create_user  order by  score desc)aa,(select (@ranknum :=0) ) b limit 5) aaa left join user bbb on aaa.create_user = bbb.id";
        return this.jdbcTemplate.queryForList(sql, new Object[]{classId});
    }

    public List<Map<String, Object>> getAvgs() {
        Long classId = SessionInfo.getClassId();
        String sql = "select aaa.*,bbb.user_login_name name from (select aa.*,(@ranknum:=@ranknum+1) as rank from (select round(avg(score),2) score,create_user from task_user_learn_log a where a.state = 2 and a.class_id = ?  and a.score_state = 2 group by create_user  order by  score desc)aa,(select (@ranknum :=0) ) b limit 5) aaa left join user bbb on aaa.create_user = bbb.id";
        return this.jdbcTemplate.queryForList(sql, new Object[]{classId});
    }

    public List<Task> getNoCompleteTasks() {
        String sql = "select group_concat(id) from task_user_learn_log where create_user = ? and state = 2";
        String ids = "";

        try {
            ids = (String)this.jdbcTemplate.queryForObject(sql, String.class, new Object[]{SessionInfo.getUserId()});
        } catch (Exception var8) {
            var8.printStackTrace();
        }

        Long userCount = this.userDao.selectCount(new QueryWrapper((new User()).setUserType(3)));
        sql = "select aa.*,bb.* from (select round(count(1)*100/" + userCount + ",0) count,task_id from task_user_learn_log where state = 2 and class_id = ? ";
        if (!ICommons.isNullOrEmpty(ids)) {
            sql = sql + "and id not in (" + ids + ")";
        }

        sql = sql + " group by task_id order by count desc limit 5)aa left join task bb on aa.task_id = bb.id ";
        List<Task> tasks = this.jdbcTemplate.query(sql, new Object[]{SessionInfo.getUser().getClassId()}, new BeanPropertyRowMapper(Task.class));
        if (tasks.size() < 5) {
            List<String> arr = new ArrayList();
            if (!ICommons.isNullOrEmpty(ids)) {
                Collections.addAll(arr, ids.split(","));
            }

            Iterator var6 = tasks.iterator();

            while(var6.hasNext()) {
                Task mt = (Task)var6.next();
                arr.add(IConvert.long2int(mt.getId()) + "");
            }

            PageHelper.startPage(1, 5 - tasks.size());
            List<Task> others = new ArrayList();
            if (arr.size() > 8) {
                others = this.taskDao.selectList((Wrapper)(new QueryWrapper()).notIn("id", arr));
            }

            tasks.addAll((Collection)others);
        }

        return tasks;
    }

    public Map<String, Object> getDatas() {
        Long classId = SessionInfo.getClassId();
        Map<String, Object> res = new HashMap();
        Long task_sum = this.taskDao.selectCount(new QueryWrapper((Object)null));
        Long task_count = this.learnLogDao.selectCount(new QueryWrapper((new TaskUserLearnLog()).setCreateUser(SessionInfo.getUserId()).setState(2)));
        res.put("task_sum", task_sum);
        res.put("task_count", task_count);
        res.put("task_percent", String.format("%.1f", (double)task_count * 100.0D / (double)task_sum));
        Integer complete_rank = 0;
        Integer complete_class = 0;
        String sql = "select aaa.rank from (select aa.*,(@ranknum:=@ranknum+1) as rank from (select count(1) count,create_user from task_user_learn_log a where a.state = 2 and a.class_id = ? group by create_user  order by  count desc)aa,(select (@ranknum :=0) ) b) aaa where aaa.create_user = ?";

        try {
            complete_rank = (Integer)this.jdbcTemplate.queryForObject(sql, new Object[]{classId, SessionInfo.getUserId()}, Integer.class);
            res.put("complete_rank", complete_rank);
        } catch (Exception var16) {
            ;
        }

        try {
            complete_class = (Integer)this.jdbcTemplate.queryForObject("select count(1) from task_user_learn_log where state = 2 and class_id = ?", new Object[]{SessionInfo.getClassId()}, Integer.class);
            res.put("complete_class", complete_class);
        } catch (Exception var15) {
            ;
        }

        Integer avg_rank = 0;
        Double avg_class = 0.0D;
        Double avg_user = 0.0D;
        sql = "select aaa.rank from (select aa.*,(@ranknum:=@ranknum+1) as rank from (select avg(score) score,create_user from task_user_learn_log a where a.state = 2  and a.score_state = 2 and a.class_id = ? group by create_user  order by  score desc)aa,(select (@ranknum :=0) ) b) aaa where aaa.create_user = ?";

        try {
            avg_rank = (Integer)this.jdbcTemplate.queryForObject(sql, new Object[]{classId, SessionInfo.getUserId()}, Integer.class);
        } catch (Exception var14) {
            ;
        }

        sql = "select round(avg(score),2) score from task_user_learn_log where class_id = ? and score_state = 2 and state = 2 union all select  round(avg(score),2) score from task_user_learn_log where class_id = ?  and score_state = 2 and state = 2 and create_user = ?";

        List result;
        try {
            result = this.jdbcTemplate.queryForList(sql, new Object[]{classId, classId, SessionInfo.getUserId()});
            if (result.size() > 0) {
                avg_class = IConvert.object2double(((Map)result.get(0)).get("score"));
                avg_user = IConvert.object2double(((Map)result.get(1)).get("score"));
            }
        } catch (Exception var13) {
            var13.printStackTrace();
        }

        res.put("avg_rank", avg_rank);
        res.put("avg_class", avg_class);
        res.put("avg_user", avg_user);
        sql = "select count(1) count from task where id not in (select a.task_id from task_user_learn_log a where a.create_user = ? and a.state = 2)";

        try {
            result = this.jdbcTemplate.queryForList(sql, new Object[]{SessionInfo.getUserId()});
            if (result.size() > 0) {
                res.put("todo_count", ((Map)result.get(0)).get("count"));
            }
        } catch (Exception var12) {
            var12.printStackTrace();
        }

        return res;
    }

    public Map<String, Object> getBarDatas() {
        Long classId = SessionInfo.getClassId();
        String sql = "select aa.*,bb.user_login_name name from (select count(1) count,create_user from task_user_learn_log a where a.state = 2 and a.class_id = ? group by create_user  order by  count desc limit 10) aa left join user bb on aa.create_user = bb.id";
        List<Map<String, Object>> res = this.jdbcTemplate.queryForList(sql, new Object[]{classId});
        List<String> x = new ArrayList();
        List<Integer> y = new ArrayList();
        Iterator var6 = res.iterator();

        while(var6.hasNext()) {
            Map<String, Object> map = (Map)var6.next();
            x.add(IConvert.object2string(map.get("name")));
            y.add(IConvert.object2int(map.get("count")));
        }

        Map<String, Object> result = new HashMap();
        result.put("x", x);
        result.put("y", y);
        result.put("all", this.taskDao.selectCount((Wrapper)null));
        return result;
    }

    public Map<String, Object> getLearnAnalyse() {
        Long classId = SessionInfo.getClassId();
        Map<String, Object> res = new HashMap();
        Long task_sum = this.taskDao.selectCount((Wrapper)null);
        Long task_count = this.learnLogDao.selectCount(new QueryWrapper((new TaskUserLearnLog()).setCreateUser(SessionInfo.getUserId()).setState(2)));
        res.put("task_sum", task_sum);
        res.put("task_count", task_count);
        res.put("task_percent", String.format("%.2f", (double)task_count * 100.0D / (double)task_sum));
        Integer complete_rank = 0;
        String sql = "select aaa.rank from (select aa.*,(@ranknum:=@ranknum+1) as rank from (select count(1) count,create_user from task_user_learn_log a where a.state = 2 and a.class_id = ? group by create_user  order by  count desc)aa,(select (@ranknum :=0) ) b) aaa where aaa.create_user = ?";

        try {
            complete_rank = (Integer)this.jdbcTemplate.queryForObject(sql, new Object[]{classId, SessionInfo.getUserId()}, Integer.class);
        } catch (Exception var12) {
            ;
        }

        res.put("complete_rank", complete_rank);
        Integer avg_rank = 0;
        Double avg_user = 0.0D;
        sql = "select aaa.rank from (select aa.*,(@ranknum:=@ranknum+1) as rank from (select avg(score) score,create_user from task_user_learn_log a where a.state = 2  and a.score_state = 2 and a.class_id = ? group by create_user  order by  score desc)aa,(select (@ranknum :=0) ) b) aaa where aaa.create_user = ?";

        try {
            avg_rank = (Integer)this.jdbcTemplate.queryForObject(sql, new Object[]{classId, SessionInfo.getUserId()}, Integer.class);
        } catch (Exception var11) {
            ;
        }

        sql = "select  round(avg(score),2) score from task_user_learn_log where class_id = ?  and score_state = 2 and state = 2 and create_user = ?";

        try {
            List<Map<String, Object>> result = this.jdbcTemplate.queryForList(sql, new Object[]{classId, SessionInfo.getUserId()});
            avg_user = IConvert.object2double(((Map)result.get(0)).get("score"));
        } catch (Exception var10) {
            ;
        }

        res.put("avg_rank", avg_rank);
        res.put("avg_user", avg_user);
        return res;
    }

    public Map<String, Object> analyseBar(Integer type, Long catalogId) {
        String sql = "";
        if (type == null) {
            type = 1;
        }

        switch(type) {
            case 1:
                sql = " round(avg(a.score),2) ";
                break;
            case 2:
                sql = " round(max(a.score),2) ";
                break;
            case 3:
                sql = " round(min(a.score),2) ";
                break;
            case 4:
                sql = " count(1) ";
        }

        sql = "select aa.*,bb.user_login_name name from (select " + sql + " count,create_user from task_user_learn_log a where a.state = 2 and a.class_id =  " + SessionInfo.getClassId();
        if (type != 4) {
            sql = sql + " and a.score_state = 2 ";
        }

        if (!ICommons.isNullOrEmpty(catalogId, true)) {
            sql = sql + " and a.catalog_id = " + catalogId;
        }

        sql = sql + " group by create_user  order by  count desc limit 10) aa left join user bb on aa.create_user = bb.id";
        List<Map<String, Object>> res = this.jdbcTemplate.queryForList(sql);
        List<String> x = new ArrayList();
        List<Object> y = new ArrayList();
        Iterator var7 = res.iterator();

        while(var7.hasNext()) {
            Map<String, Object> map = (Map)var7.next();
            x.add(IConvert.object2string(map.get("name")));
            y.add(map.get("count"));
        }

        Map<String, Object> result = new HashMap();
        result.put("x", x);
        result.put("y", y);
        if (type == 4) {
            result.put("all", this.taskDao.selectCount((Wrapper)null));
        } else {
            result.put("all", 100);
        }

        return result;
    }
}
